/*
 * @lc app=leetcode.cn id=142 lang=cpp
 *
 * [142] 环形链表 II
 */

#include "include.h"

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if (head == nullptr){return nullptr;}

        ListNode * pointerFast = head;
        ListNode * pointerSlow = head;
        while (1){
            if (pointerFast->next == nullptr){return nullptr;}
            pointerFast = pointerFast->next;

            if (pointerSlow->next == nullptr){return nullptr;}
            pointerSlow = pointerSlow->next;
            if (pointerSlow->next == nullptr){return nullptr;}
            pointerSlow = pointerSlow->next;

            if (pointerFast == pointerSlow){
                ListNode * pointerRestart = head;
                while(1) {
                    if (pointerRestart == pointerSlow){return pointerRestart;}
                    pointerRestart = pointerRestart->next;
                    pointerSlow = pointerSlow->next;
                }
            }
        }
    }
};
// @lc code=end

